package fr.matwizz.mesdevoirs.android.adapter;

import android.content.Context;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.util.List;

import fr.matwizz.mesdevoirs.app.R;
import fr.matwizz.mesdevoirs.serveur.model.Agenda;

/**
 * Created by RGA on 27/04/14.
 */
public class AgendaAdapter extends BaseAdapter{

    private List<Agenda> agendas;
    private LayoutInflater inflater;

    public AgendaAdapter(final ListView list, Context context) {
        this.inflater = LayoutInflater.from(context);
        list.setAdapter(this);
        registerDataSetObserver(new DataSetObserver() {
            public void onChanged() {
                list.invalidateViews();
            }
        });
    }

    @Override
    public int getCount() {
        if (agendas == null) {
            return 0;
        } else {
            return agendas.size();
        }
    }

    @Override
    public Object getItem(int position) {
        return agendas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        TaskHolder holder;

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.agenda, null);
            holder = new TaskHolder();
            holder.name = (TextView) convertView.findViewById(R.id.name);
            convertView.setTag(holder);
        } else {
            holder = (TaskHolder) convertView.getTag();
        }

        if (position < getCount()) {
            Agenda agenda = (Agenda) getItem(position);
            holder.name.setText(agenda.getName());
        }

        return convertView;
    }

    public void setAgendas(List<Agenda> agendas) {
        this.agendas = agendas;
        notifyDataSetChanged();
    }

    public void addAgenda(Agenda agenda) {
        if (!agendas.contains(agenda)) {
            agendas.add(agenda);
            notifyDataSetChanged();
        }
    }

    public void removeAgenda(Agenda agenda) {
        agendas.remove(agenda);
        notifyDataSetChanged();
    }

    /**
     * Holder class :
     * Permet de ne pas multiplier le nombre
     * d'instance de View utilisées pour
     * l'affichae des utilisateurs dans la
     * ListView
     */
    static class TaskHolder {
        TextView name;
        TextView id;
    }
}
